from django.shortcuts import render
from . import models
from django.shortcuts import render, redirect,HttpResponse
import hashlib
from .forms import RegisterForm
from .models import common_user as User

def hash_code(s, salt='login'):
    h = hashlib.sha256()
    s += salt
    h.update(s.encode())  # update方法只接收bytes类型
    return h.hexdigest()

def register(request):
        if request.session.get('is_login', None):
            # 登录状态不允许注册。你可以修改这条原则！
            return redirect("/index/")
        if request.method == "POST":
            register_form = RegisterForm(request.POST)
            if register_form.is_valid():  # 获取数据
                username = register_form.cleaned_data['username']
                password1 = register_form.cleaned_data['password1']
                password2 = register_form.cleaned_data['password2']
                email = register_form.cleaned_data['email']
                sex = register_form.cleaned_data['sex']
                if password1 != password2:  # 判断两次密码是否相同
                    message = "两次输入的密码不同！"
                    return render(request, 'register.html', locals())
                else:
                    same_name_user = User.objects.filter(name=username)
                    if same_name_user:  # 用户名唯一
                        message = '用户已经存在，请重新选择用户名！'
                        return render(request, 'register.html', locals())
                    same_email_user = User.objects.filter(email=email)
                    if same_email_user:  # 邮箱地址唯一
                        message = '该邮箱地址已被注册，请使用别的邮箱！'
                        return render(request, 'register.html', locals())

                    # 当一切都OK的情况下，创建新用户

                    new_user = User.objects.create()
                    new_user.name = username
                    new_user.password = hash_code(password1)  # 使用加密密码
                    new_user.email = email
                    new_user.sex = sex
                    new_user.save()
                    return redirect('/index/')  # 自动跳转到登录页面
            else:
                message = "验证码错误！"
        register_form = RegisterForm()
        return render(request, 'register.html', locals())

def login(request):
    return render(request, 'login.html')
# Create your views here.
